#!/usr/bin/python3
# -*- coding: utf-8 -*-

from coreweb import get, post
from datetime import datetime
from sqlalchemy import func

import db

@get('/blogs', 'blogs.html')
async def blogs(*, request, page=1,page_size=5):
    session = db.create_session()
    page_index = int(page)
    total = session.query(func.count(db.Blog.id)).scalar()
    pages = (total - 1) // page_size + 1
    if pages > 0:
        result = [blog for blog in session.query(db.Blog).filter().limit(page_size).offset((page_index-1)*page_size)]
        if pages <= 5:
            page_list = range(1, pages + 1)
        else:
            if page_index > 3 and page_index < pages - 3:
                page_list = range(page_index - 2, page_index + 3)
            if page_index <= 3:
                page_list = range(1, 6)
            if page_index < pages - 3:
                page_list = range(pages -5, pages + 1)
        pre = {
            'status': page_index > 1, 
            'num': page_list[0] - 1 if page_list[0] - 1 > 0 else 1
        }
        next = {
            'status': page_index < pages, 
            'num': page_list[-1] + 1 if page_list[-1] + 1 <= pages else pages
        }
        data = {"blogs": result, 'page': {'index': page_index, 'pages': pages, 'total': total, 'pre': pre, 'next': next, 'list': page_list}}
    else:
        data = {'blogs': None, 'page': None}
    return data

@get('/blog/edit', 'blog_edit.html')
async def blog_edit(*, request):
    user = request.__user__
    if not user:
        return 'redirect:/login'
    return {}

@get('/blog/edit/{id}', 'blog_edit.html')
async def blog_edit_id(*, id, request):
    session = db.create_session()
    blog = session.query(db.Blog).filter_by(id=id).first()
    user = request.__user__
    if not user or blog.user_id != user.id:
        return 'redirect:/blogs'
    return {'blog': blog}

@post('/blog/delete/{id}')
async def blog_delete_id(*, id, request):
    session = db.create_session()
    blog = session.query(db.Blog).filter_by(id=int(id)).first()
    user = request.__user__
    if user and (user.admin or blog.user_id == user.id):
        session.delete(blog)
        session.commit()
    else:
        return {'code': -1, 'msg': '没有删除该blog的权限'}
    return {'code': 0, 'msg': '删除成功'}

@post('/blog/save')
async def do_blog_edit(*, name, summary, content, id, request):
    if not name or not name.strip():
        return {'code': -1, 'field': 'name', 'msg': 'name is null'}
    if not summary or not summary.strip():
        return {'code': -1, 'field': 'summary', 'msg': 'summary is null'}
    if not content or not content.strip():
        return {'code': -1, 'field': 'content', 'msg': 'content is null'}
    session = db.create_session()
    if not id or not id.strip() or id.isdigit():
        blog = session.query(db.Blog).filter_by(id=int(id)).first()
        blog.name = name
        blog.summary = summary
        blog.content = content
        blog.updated_at = datetime.now()
        session.commit()
    else:
        user = request.__user__
        if user:
            blog = db.Blog(name=name, user_id=user.id, user_name=user.name, user_image=user.image, summary=summary, content=content)
        else:
            blog = db.Blog(name=name, summary=summary, content=content)
        session.add(blog)
        session.commit()
    data = {'code': 0, 'msg': '编辑成功'}
    return data